package com.diamond.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class ServerUtils {
	//用于服务器访问 的安全验证
	public final static String SECRET = "Diamond(IS ME) is a good man!!!And I want resignation at this time!!! The company is not so good!!! and I guess no one will see this code!!!LOL 2016-1-7 11:13:04";
	
	public static String getRandomString(int lenght) {
		String str = "";
		Random r = new Random();
		for (int i = 0; i < lenght; i++) {
			if (r.nextInt(2) == 0) {
				str += (char) ('a' + r.nextInt(26)) + "";
			} else {
				str += (char) ('A' + r.nextInt(26)) + "";
			}
		}
		return str;
	}
	
	public static String map2String(Map<String,String>params) throws UnsupportedEncodingException{
		if(params==null||params.size()==0){
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for(String key : params.keySet()){
			sb.append(key);
			sb.append("=");
			if(params.get(key)!=null){
				sb.append(URLEncoder.encode(String.valueOf(params.get(key)),"utf-8"));
			}
			sb.append("&");
		}
		return sb.substring(0, sb.length()-1);
	}

	public static String createSign(Map<String,String> map){
		List<String> keySortList = new ArrayList<String>(map.keySet());
		Collections.sort(keySortList);
		StringBuffer params =new StringBuffer();
		for(int i=0;i<keySortList.size();i++){
			String k = keySortList.get(i);
			String v = map.get(k);
			if(StringUtils.isBlank(v)||"sign".equals(k)) 
				continue;
			params.append(k);
			params.append("=");
			params.append(v);
			params.append("&");
		}
		params.append("key="+SECRET);	
		String sign = ApplicationUtils.md5Hex(params.toString()).toUpperCase();
		return sign;
	}
	
	public static boolean isSign(Map<String,String> mapData){
		String sign = mapData.get("sign");
		String generateSign = createSign(mapData);
		return generateSign.equals(sign);
	}

	public static boolean isSign(HttpServletRequest request) {
		Map<String,String> map = new HashMap<String, String>();
		for(String name:request.getParameterMap().keySet()){
			String value=request.getParameter(name);
			map.put(name, value);
		}
		return isSign(map);
	}
	
}
